package services

import (
	"bytes"
	"context"
	"crypto/tls"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"io"
	"net/http"
	"net/url"
	"strings"
	"time"
	"wecom_rebot/common"
	"wecom_rebot/core"
	"wecom_rebot/models"
)

var adSearchWithoutLogger *logrus.Logger

// InitAdSearchWithoutLogger 移除 init() 函数，改为显式初始化函数
func InitAdSearchWithoutLogger() {
	// 确保在 common 初始化后调用
	adSearchWithoutLogger = core.InitLogger(common.LogsErrorMap[12])
}

type getDocument struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		Result      bool `json:"result"`
		CompanyList []struct {
			CompanyId   int    `json:"companyId"`
			CompanyName string `json:"companyName"`
			LicenseNo   string `json:"licenseNo"`
			LicenseType int    `json:"licenseType"`
		} `json:"companyList"`
	} `json:"data"`
}

type HugeAdSearchWithoutService struct{}

func (s *HugeAdSearchWithoutService) Handle(msgId int, subjectName, roomId string, content []string, jobId uint64) error {
	var msg = &models.Msg{}

	fmt.Println("adSearchWithoutLogger", "原始结构Id：", msgId)
	// 获取数据
	err := common.DB.Where("id = ?", msgId).First(&msg).Error
	if err != nil {
		adSearchWithoutLogger.Error("巨量AD获取数据失败", common.LogsErrorMap[2], msgId, err)
		return err
	}

	adSearchWithoutLogger.Info("adSearchWithoutLogger", "原始结构：", content)

	// 处理需要的数据结构
	customerName, err := s.analyzeContent(content)
	if err != nil {
		adSearchWithoutLogger.Error(err)
		return err
	}

	if customerName == "" {
		return errors.New("客户名称不能为空")
	}

	err = checkEnglishParentheses(customerName, msg)
	if err != nil {
		adSearchWithoutLogger.Error("括号检测错误", err)
		return err
	}

	// 移除功能行
	msg.Content = RemoveTitle(msg)
	fmt.Println("adSearchWithoutLogger", customerName, "移除后的结构：", msg, "广告主信息：", content)

	rdb := core.InitRedis(13)
	ctx := context.Background()

	cookies, err := rdb.Get(ctx, "laravel_database_oead_adv_cookies").Result()

	fmt.Println("adSearchWithoutLogger", "Cookies:", cookies)

	// 第一步 获取证件号码
	documentList, err := s.getDocumentNumber("1629698414782477", customerName, cookies)
	if err != nil {
		adSearchWithoutLogger.Warnf("获取证件号码失败: %v", err)
		return errors.New("媒体提示4：" + err.Error())
	}

	searchWitch, err := s.getSearchWithout(customerName, documentList.Data.CompanyList[0].LicenseNo, cookies, documentList.Data.CompanyList[0].LicenseType)
	if err != nil {
		adSearchWithoutLogger.Error("获取直客信息失败", common.LogsErrorMap[12], err)
		return errors.New("获取直客信息失败" + err.Error())
	}

	// 构建直客信息展示文本
	customerInfo := buildCustomerInfoMessage(searchWitch, customerName)

	contacts, err := s.getContactsPerson(customerName, cookies)
	if err != nil {
		adSearchWithoutLogger.Error("获取联系人信息失败", common.LogsErrorMap[12], customerName, err)
		return errors.New("获取联系人信息失败" + err.Error())
	}

	// 构建联系人信息
	contactInfo := buildContactInfoMessage(contacts)

	// 合并直客信息和联系人信息
	fullInfo := customerInfo + "\n" + contactInfo

	// 发送完整信息
	err = sendContactInfo(msg, fullInfo)
	if err != nil {
		adSearchWithoutLogger.Warnf("发送信息失败: %v", err)
		return err
	}

	return nil
}

// 获取证件号码
func (s *HugeAdSearchWithoutService) getDocumentNumber(agentId, lifeAccountId string, cookies string) (*getDocument, error) {
	documentUrl := fmt.Sprintf("https://agent.oceanengine.com/agent/adv-create/profile/company-name-check/v2?agentId=%s&companyName=%s", agentId, lifeAccountId)

	var result getDocument
	err := s.SendCurlRequest(documentUrl, nil, cookies, "GET", "", &result)
	if err != nil {
		return nil, err
	}

	adSearchWithoutLogger.Info("获取证件号码：", result)

	if result.Code != 0 {
		adSearchWithoutLogger.Error("获取证件号码失败", result)
		return nil, fmt.Errorf("获取证件号码失败: %s", result.Msg)
	}

	return &result, nil
}

// 构建联系人信息展示文本
func buildContactInfoMessage(contactsResponse *ContactResponse) string {
	var str strings.Builder
	str.WriteString("联系人信息：\n")

	if contactsResponse.Code == 0 && len(contactsResponse.Data.Contacts) > 0 {
		// 遍历联系人信息
		for _, item := range contactsResponse.Data.Contacts {
			str.WriteString(fmt.Sprintf("联系人名称：%s\n联系人手机号：%s\n联系人邮箱：%s\n联系人身份证号：%s\n",
				item.ContactName,
				item.MaskMobile,
				item.MaskEmail,
				item.MaskIdCardNo))
		}
	} else {
		// 未找到联系人信息
		str.WriteString("未找到联系人信息\n")
	}

	return str.String()
}

// 发送联系人信息
func sendContactInfo(msg *models.Msg, contactInfo string) error {
	// 构建完整消息
	fullMessage := fmt.Sprintf("%s\n-----------------------------------\n%s", msg.Content, contactInfo)

	// 发送消息
	err := BendiSendText(fullMessage, msg.RoomID, msg.Sender)
	if err != nil {
		adSearchWithoutLogger.Errorf("发送联系人信息失败: %v", err)
		return err
	}

	return nil
}

// 构建直客信息展示文本
func buildCustomerInfoMessage(searchResponse *SearchWithoutResponse, customerName string) string {
	var str strings.Builder
	str.WriteString("直客信息：\n")

	if searchResponse.Code == 0 && len(searchResponse.Data) > 0 {
		// 成功获取直客信息
		for _, item := range searchResponse.Data {
			str.WriteString(fmt.Sprintf("直客名称：%s\n直客ID：%d\n一二级行业：%s/%s\n",
				item.CustomerName,
				item.CustomerID,
				item.FirstIndustry,
				item.SmallIndustry))
		}
	} else {
		// 未找到直客信息，提供手动设置链接
		encodedName := url.QueryEscape(customerName)
		link := fmt.Sprintf("https://web.disbursements.ecoremedia.net/#/other/account_industry?account_name=%s", encodedName)
		str.WriteString(fmt.Sprintf("未找到直客信息，请手动设置行业：\n%s\n", link))
	}

	return str.String()
}

// 在 HugeAdCopyAccountService 中添加
func (s *HugeAdSearchWithoutService) getContactsPerson(companyName, cookies string) (*ContactResponse, error) {
	sprintfUrl := fmt.Sprintf("https://agent.oceanengine.com/agent/adv-create/profile/query-qualification-contact?agentId=1629698414782477&companyName=%s", companyName)

	var response ContactResponse
	err := s.SendCurlRequest(sprintfUrl, nil, cookies, "GET", "", &response)
	if err != nil {
		adSearchWithoutLogger.Errorf("获取联系人信息失败: %v", err)
		return nil, err
	}

	if response.Code != 0 {
		adSearchWithoutLogger.Warnf("接口返回错误: %s", response.Msg)
		return nil, fmt.Errorf("接口错误: %s", response.Msg)
	}

	if len(response.Data.Contacts) == 0 {
		adSearchWithoutLogger.Warn("联系人信息为空")
		return nil, fmt.Errorf("未找到联系人信息")
	}

	return &response, nil
}

// getSearchWithout 获取直客信息
func (s *HugeAdSearchWithoutService) getSearchWithout(accountName, licenseNo, oeAdCookies string, licenseType int) (*SearchWithoutResponse, error) {
	sprintfUrl := fmt.Sprintf("https://agent.oceanengine.com/agent/adv-create/customer/query/?customerName=%s&isQianchuan=false&licenseNo=%s&licenseType=%d", accountName, licenseNo, licenseType)

	var response SearchWithoutResponse
	err := s.SendCurlRequest(sprintfUrl, nil, oeAdCookies, "GET", "", &response)
	if err != nil {
		adSearchWithoutLogger.Errorf("获取直客信息失败: %v", err)
		return nil, err
	}

	// 记录完整响应
	adSearchWithoutLogger.Infof("getSearchWithout获取直客完整信息: %+v", response)

	// 检查返回码不为0的情况
	if response.Code != 0 {
		adSearchWithoutLogger.Warnf("getSearchWithout获取直客信息失败: %s", response.Msg)
		return nil, fmt.Errorf("接口返回错误: %s", response.Msg)
	}

	// 检查data为空的情况
	if len(response.Data) == 0 {
		adSearchWithoutLogger.Warnf("getSearchWithout未找到对应的授权信息: %s", response.Msg)
		return nil, fmt.Errorf("未找到直客信息: %s", response.Msg)
	}

	return &response, nil
}

// analyzeContent 解析内容为广告主信息数组
func (s *HugeAdSearchWithoutService) analyzeContent(content []string) (string, error) {
	// 初始化结果变量
	var customerName string

	// 遍历内容行
	for _, line := range content {
		// 账户名称
		if strings.HasPrefix(line, "客户名称:") {
			customerName = strings.TrimSpace(strings.TrimPrefix(line, "客户名称:"))
		}
	}
	if customerName == "" {
		adSearchWithoutLogger.Warn("未解析到客户名称")
		return "", errors.New("解析参数失败: 缺少客户名称")
	}

	return customerName, nil
}

// SendCurlRequest 发送HTTP请求
func (s *HugeAdSearchWithoutService) SendCurlRequest(url string, postData interface{}, xhsCookies string, method string, oeCsrfToken string, result interface{}) error {
	// 创建请求上下文
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// 序列化POST数据
	var bodyReader io.Reader
	if postData != nil {
		jsonData, err := json.Marshal(postData)
		if err != nil {
			return fmt.Errorf("JSON序列化失败: %v", err)
		}
		bodyReader = bytes.NewBuffer(jsonData)
	}

	// 创建请求
	req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)
	if err != nil {
		return fmt.Errorf("创建请求失败: %v", err)
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/json;charset=UTF-8")
	req.Header.Set("Cookie", xhsCookies)
	if oeCsrfToken != "" {
		req.Header.Set("Cg-Csrf-Token", oeCsrfToken)
	}

	// 创建自定义客户端
	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
	}

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("请求失败: %v", err)
	}
	defer resp.Body.Close()

	// 读取响应体
	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("读取响应失败: %v", err)
	}

	adSearchWithoutLogger.Info("获取后得参数格式：", string(respBody))

	if result != nil {
		if err := json.Unmarshal(respBody, &result); err != nil {
			return fmt.Errorf("JSON解析失败: %v", err)
		}
	}
	return nil
}

// 检查是否包含英文括号
func checkEnglishParentheses(customerName string, msg *models.Msg) error {
	if strings.Contains(customerName, "(") || strings.Contains(customerName, ")") {
		// 记录警告
		adSearchWithoutLogger.Warn("检测到英文括号")

		// 构建提示消息
		errorMsg := "提示：必须使用中文括号（），请重新填写。"
		fullMessage := fmt.Sprintf("%s\n-----------------------------------\n%s", msg.Content, errorMsg)

		// 发送提示消息
		err := BendiSendText(fullMessage, msg.RoomID, msg.Sender)
		if err != nil {
			adSearchWithoutLogger.Errorf("发送括号提示消息失败: %v", err)
		}

		// 返回错误中断流程
		return fmt.Errorf(errorMsg)
	}
	return nil
}
